import React, { Component } from 'react';
import { RadioChangeEvent } from 'antd';
import { FormInstance } from 'antd/es/form';
import {
  Card,
  Button,
  Descriptions,
  Table,
  Form,
  Radio,
  Select,
  Space,
  Input,
  message,
  Typography,
} from 'antd';
import router from 'umi/router';
import ContentModal from '@/components/ContentModal';
import { fromJS } from 'immutable';
import { connect } from 'dva';
import styles from './doSend.less';

const { Option } = Select;
const { Text } = Typography;
const { TextArea } = Input;
const mapStateToProps = (state: any) => {
  return {
    audienceList: state.base?.data?.data || [],
  };
};

class messageTemplate_doSend extends Component {
  state = {
    dataSource: [],
    isLayer: false,
    layerData: '',
    templateData: {},
    selectVal: '',
    btnLoading: false,
    selectType: 1,
    btnLoading:false
  };
  refInp = React.createRef();
  formRef = React.createRef<FormInstance>();
  componentDidMount() {
    const templateData = JSON.parse(sessionStorage.getItem('templateData'));
    const contentList = this.getMatchedStrs(templateData?.tplContent) || [];
    // 去重处理
    const set = [...new Set(contentList)];
    const list = set.map(item => {
      return { key: item, value: '' };
    });

    const { dispatch } = this.props;
    dispatch({
      type: 'base/add',
      payload: {
        url: '/audience/group/list',
        // projectId: templateData?.projectId,
      },
    });

    this.setState({
      dataSource: list,
      templateData,
    });
  }

  // 获取${xxx}的内容
  getMatchedStrs = (str = '') => {
    {
      const reg = /\$\{(.+?)\}/g;
      let list = [];
      let result = null;
      do {
        result = reg.exec(str);
        result && list.push(result[1]);
      } while (result);
      return list;
    }
  };
  titleFn = (txt: string) => {
    return (
      <span style={{ color: '#559BFF' }}>
        <span style={{ fontSize: 24 }}>| </span>
        {txt}
      </span>
    );
  };
  handleChange = (val: string) => {
    this.setState({
      selectVal: val,
    });
  };
  handleChangeType = (e: RadioChangeEvent) => {
    this.setState({
      selectType: e.target.value,
    });
  };
  handleSaveRowData = (i: number, val: string) => {
    const list = fromJS(this.state?.dataSource || []);
    const newList = list.setIn([i, 'value'], val);
    this.setState({
      dataSource: newList.toJS(),
    });
  };
  goBackFn = () => {
    router.goBack();
  };
  changeVisible = () => {
    this.setState({
      isLayer: false,
    });
  };
  previewFn = () => {
    const { templateData, dataSource } = this.state;
    let str = templateData?.tplContent;
    dataSource.forEach(e => {
      str = str.split('${' + e.key + '}').join(e.value);
    });

    this.setState({
      isLayer: true,
      layerData: str,
    });
  };
  primaryFn = () => {
    const { dataSource, selectVal, templateData, selectType } = this.state;
    const topic = this.refInp?.current?.input?.value;
    const { msgCd, defaultPushChannel, projectId } = templateData;
    const isChannel = defaultPushChannel == 3 || defaultPushChannel == 4;

    const audience = this.formRef.current?.getFieldValue('audience');
    const audienceId = this.formRef.current?.getFieldValue('audienceId');
    if (selectType === 1 && defaultPushChannel != 3 && !audience) {
      message.error('请选择受众对象组');
      return false;
    }
    if (selectType === 2 && defaultPushChannel != 3 && !audienceId) {
      message.error('请输入受众对象');
      return false;
    }

    /* if (!selectVal && defaultPushChannel != 3) {
      message.error('请选择受众对象组');
      return false;
    } */
    // 类型为3和4的时候
    if (!topic && isChannel) {
      message.error('请输入Topic');
      return false;
    }
    const { dispatch } = this.props;
    // const obj = JSON.parse(selectVal || '{}');
    const obj = JSON.parse(audience || '{}');
    const keyValue = {};
    let tempVals = {};
    if (selectType === 1) {
      tempVals = {
        audienceGroupId: obj.sid,
        audienceGroupName: obj.objectGroupName,
      };
    } else if (selectType === 2) {
      tempVals = {
        receiverId: audienceId,
      };
    }

    dataSource.forEach((e: any) => {
      Object.assign(keyValue, {
        [e.key]: e.value,
      });
    });

    const params = {
      // audienceGroupId: obj.sid,
      // audienceGroupName: obj.objectGroupName,
      keyValue,
      manualFlag: 1,
      msgCd,
      projectId,
      defaultPushChannel: isChannel ? defaultPushChannel : '',
      topic,
      ...tempVals,
    };
    this.setState({ btnLoading: true });
    dispatch({
      type: 'http/postObj',
      payload: { url: '/message/template/messagePush', ...params },
      callback: res => {
        if (res.statusCode === '0') {
          router.goBack();
          //   message.success({
          //     content: '发送成功',
          //     onClose: () => {

          //     },
          //   });
          message.success('发送成功');
        }
        this.setState({ btnLoading: false });
      },
    });
  };
  render() {
    const { defaultPushChannel = '' } = this.state?.templateData;
    const { selectType, btnLoading } = this.state;
    const columns = [
      {
        title: '变量',
        dataIndex: 'key',
        key: 'key',
      },
      {
        title: '* 值',
        dataIndex: 'value',
        key: 'value',
        render: (text, record, index) => {
          return (
            <Input
              defaultValue={text}
              maxLength={50}
              onChange={e => {
                this.handleSaveRowData(index, e.target.value);
              }}
            />
          );
        },
      },
    ];
    return (
      <>
        <Card style={{ padding: '20px' }}>
          <Descriptions title={this.titleFn('替换变量')} column={1}>
            <Descriptions.Item label="模板内容">
              <Table
                dataSource={this.state.dataSource}
                columns={columns}
                bordered
                pagination={{ position: ['none'] }}
                style={{ minWidth: '300px' }}
              />
            </Descriptions.Item>
            <div style={{ padding: '0 70px 15px' }}>
              <Button onClick={this.previewFn}>预览</Button>
            </div>
          </Descriptions>
          {defaultPushChannel != 3 && (
            <>
              {/* <Descriptions title={this.titleFn('接受对象')}>
              <Descriptions.Item span={12} label="受众对象组">
                <Select placeholder="请选择" style={{ width: 200 }} onChange={this.handleChange}>
                  {this.props.audienceList.map((e: any) => (
                    <Option value={JSON.stringify(e)} key={e.sid}>
                      {e.objectGroupName}
                    </Option>
                  ))}
                </Select>
              </Descriptions.Item>
            </Descriptions> */}
              <Form className={styles.form} ref={this.formRef} name="ref">
                <Radio.Group
                  onChange={this.handleChangeType}
                  value={selectType}
                  style={{ width: '100%' }}
                >
                  <Space direction="vertical" style={{ width: '100%' }}>
                    {/* <Form.Item name="sid" noStyle>
                    <Input type="hidden" />
                  </Form.Item> */}
                    <Form.Item noStyle>
                      <Radio value={1}></Radio>
                      <div style={{ display: 'inline-block' }}>
                        <Form.Item name="audience" label="受众对象组" rules={[]}>
                          <Select placeholder="请选择" style={{ width: 360 }}>
                            {this.props.audienceList.map((e: any) => (
                              <Option value={JSON.stringify(e)} key={e.sid}>
                                {e.objectGroupName}
                              </Option>
                            ))}
                          </Select>
                        </Form.Item>
                      </div>
                    </Form.Item>
                    <Form.Item noStyle>
                      <Radio
                        className={styles.audienceId}
                        value={2}
                        style={{ alignItems: 'flex-start' }}
                      ></Radio>
                      <div style={{ display: 'inline-block' }}>
                        <Form.Item name="audienceId" label="受众对象" rules={[]}>
                          <TextArea
                            rows={3}
                            style={{ width: 360 }}
                            placeholder="受众对象为消息的接收方，包括用户ID/手机号/Topic名称/JSON串等，如：/TSP/IVI"
                            maxLength={500}
                          />
                        </Form.Item>
                      </div>
                    </Form.Item>
                  </Space>
                </Radio.Group>
              </Form>
            </>
          )}

          {(defaultPushChannel == 3 || defaultPushChannel == 4) && (
            <Descriptions title={this.titleFn('Topic')}>
              <Descriptions.Item label="Topic名称">
                <Input ref={this.refInp} style={{ width: 360 }} />
                {defaultPushChannel == 3 && (
                  <Text type="secondary" style={{ paddingLeft: '10px' }}>
                    如：TSP_IVI
                  </Text>
                )}
                {defaultPushChannel == 4 && (
                  <Text type="secondary" style={{ paddingLeft: '10px' }}>
                    如: /TSP/IVI
                  </Text>
                )}
              </Descriptions.Item>
            </Descriptions>
          )}
          <div style={{ display: 'flex', justifyContent: 'flex-end', paddingTop: '20px' }}>
            <Space>
              <Button loading={btnLoading} onClick={this.goBackFn}>
                取消
              </Button>
              <Button type="primary" loading={btnLoading} onClick={this.primaryFn}>
                确认
              </Button>
            </Space>
          </div>
        </Card>
        <ContentModal
          title="预览"
          width="50%"
          changeVisible={this.changeVisible}
          visible={this.state.isLayer}
          formatData={true}
          detailModelData={this.state.layerData}
        />
      </>
    );
  }
}
export default connect(mapStateToProps)(messageTemplate_doSend);
